<?php

/**
 * Description of ContainerController
 *
 * @author Eugene I. Nezhuta
 */
class Backend_ContainerController extends RCMS_Core_BaseController {

/**
 * Special parser that creates seo for this site.
 *
 * @var RCMS_Object_Parser_SeoParser
 */
	protected $_seoParser = null;

	public function init() {
		parent::init();
		$this->_checkLogin(array(), array(RCMS_Object_User_User::USER_ROLE_MEMBER));
		$this->_model = new Backend_ContainerModel();
		$this->_seoParser = new RCMS_Object_Parser_SeoParser();
		$this->view->currTheme = $this->_session->currentThemeName;
	}

	public function indexAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
	}

	/**
	 * Add content container (AJAX called in js/seestem.js)
	 *
	 * @author Eugene I. Nezhuta
	 */
	public function addcontentAction() {
        $this->_helper->viewRenderer->setNoRender(true);
		$pagesArray = $this->_model->selectPagesIdsAndNavigationName();
		$formsArray = $this->_model->selectAllForms();
		$featuredAreas = $this->getFeaturedAreasNameAsString();
		$this->_helper->getHelper('layout')->disableLayout();
		$this->view->downloadFiles = RCMS_Tools_FilesystemTools::scanDir($this->_config->website->website->path . $this->_config->website->website->downloads);
		$this->view->fa = array_keys($this->_model->selectFeaturedAreasNames());
        $this->view->fp = $this->_model->SelectAllPages();
        $this->view->listFolders = RCMS_Tools_FilesystemTools::getDirectories($this->_config->website->website->path.$this->_config->website->website->images);
		$this->view->galleries = RCMS_Tools_FilesystemTools::getDirectories($this->_config->website->website->path.$this->_config->website->website->galleries);
		$this->view->forms = $formsArray;
		$this->view->pages = $pagesArray;
		$this->view->variables = $this->_model->selectAllVariables();
		$widthImgs = $this->_model->selectConfigForImage();
		$this->view->widthSmallImg = $widthImgs['img_small']['value'];
		$this->view->widthMediumImg = $widthImgs['img_medium']['value'];
		$this->view->widthLargeImg = $widthImgs['img_large']['value'];
		$this->_linkListUrlForTinyMCEAction();
		$this->view->listCategories = $this->_model->selectAllCategories();
        $this->view->users = $this->_model->selectAllUsers();

		$form = new RCMS_Form_TextcontainerForm();
		$form->getElement('featuredareas')->setValue($featuredAreas);
        $form->getElement('blog')->setValue(0);
		$form->setDecorators(array(
			array('ViewScript', array('viewScript' => 'forms/addcontent.phtml'))
		));
		$this->view->form = $form;

		$pageId = $this->getRequest()->getParam('pageId');
		if(empty ($pageId)) {
			$pageId = 0;
		} else {
			$this->view->pId = $pageId;
			$form->getElement("pageId")->setValue($pageId);
		}
		$name = $this->getRequest()->getParam('name');
		$this->view->name = $name;

		//inspired form
		$page = new RCMS_Object_Page_Page($pageId);
		$inspiredForm = new RCMS_Form_InspiredForm();
		$inspiredForm->getElement('h1')->setValue($page->getH1Tag());
		$inspiredForm->setDecorators(array(
			array('ViewScript', array('viewScript' => 'forms/inspired.phtml'))
		));
		if($page->getProtected()) {
			$this->view->protected = true;
		}
		$this->view->currentPageId = $page->getId();
		$this->view->currentNavigationName = trim($page->getNavName());
		$this->view->inspiredForm = $inspiredForm;
		//end of inspired form
		if(!$this->getRequest()->isPost()) {
			$ctype = $this->getRequest()->getParam('type');
			$form->getElement('ctype')->setValue($ctype);
		}
		if($this->getRequest()->isPost()) {
			if($this->view->form->isValid($this->getRequest()->getParams())) {
				$user = unserialize($this->_session->currentUser);
				$containerFormData = $this->view->form->getValues();
				$container = new RCMS_Object_Container_Container();
				$container->setName($name);
				$ctype = $containerFormData['ctype'];
				$container->setType(($ctype && $ctype == RCMS_Object_Container_Container::C_TYPE_STATIC) ? RCMS_Object_Container_Container::C_TYPE_STATIC : RCMS_Object_Container_Container::C_TYPE_CONTENT);
				$container->setContent($containerFormData['admincontentarea']);
				$container->setUserId($user->getId());
				$container->setPageId($pageId);
                $container->setIsBlog($containerFormData['blog']);
				// $publishContent =  $this->getRequest()->getParam('publish_content');

				$container->setPublished($containerFormData['publish_content']);
				$date = '';
				if (isset($containerFormData['publish_content']) && $containerFormData['publish_content']==1) {
					$date = $this->generateTodaysDate();
				} else {
					if(isset($containerFormData['publish_on_date']) && $containerFormData['publish_on_date']==1) {
						if( trim($containerFormData['datepicker']) != '') {
							$date = $this->proccessPublishingDateToSql($containerFormData['datepicker']);
						}
					}
				}
				$container->setPublishingDate($date);
				$container->setId($container->save());
				$this->_session->resaveRaw = true;
				//making seo here.
				if(!$this->_seoParser->applyDeeplinks($container->getId())) {
					$this->_seoParser->setContentForParsing($container->getContent());
					$this->_seoParser->updateLinkReference($container->getId());
				}
                if ($container->isBlog()) {
                    $this->_pingBlogs($page);
                }
				//$this->_seoParser->replaceDeeplinksInContent();
				echo 'success'; return;
			}
		}
		echo $this->_translator->processScreen($this->view->render($this->getViewScript()));
	}

	/**
	 * Edit text container (AJAX called in js/seestem.js)
	 *
	 * @author Eugene I. Nezhuta
	 */
	public function editcontentAction() {
        $this->_helper->viewRenderer->setNoRender(true);
		$this->_helper->getHelper('layout')->disableLayout();

		$form = new RCMS_Form_TextcontainerForm();
		$form->setDecorators(array(
			array('ViewScript', array('viewScript' => 'forms/editcontent.phtml'))
		));
		$this->view->form = $form;
		$containerId = $this->getRequest()->getParam('id');
		$this->view->containerId = $containerId;
		$container = new RCMS_Object_Container_Container($containerId);
		$this->view->containerName = $container->getName();
		$form->getElement('admincontentarea')->setValue($container->getContent());
		$form->getElement('publish_content')->setValue($container->getPublished());
		$form->getElement('pageId')->setValue($container->getPageId());
        $form->getElement('blog')->setValue($container->isBlog() === true ? 1 : 0);
		if ($container->getPublished() != 1 && $container->getPublishingDate() != '' && $container->getPublishingDate() != '0000-00-00 00:00:00') {
			$form->getElement('datepicker')->setValue( $this->proccessPublishingDateFromSql($container->getPublishingDate()));
			$form->getElement('publish_on_date')->setValue(0);
		}
		if ($container->getPublished() == 0) {
			$form->getElement('publish_on_date')->setValue(0);
		}
		if ($container->getPublishingDate() != '' && $container->getPublishingDate() != '0000-00-00 00:00:00') {
			$form->getElement('publish_on_date')->setValue(1);
		}
        $page = new RCMS_Object_Page_Page($container->getPageId());

        if(!$this->getRequest()->isPost()) {
			$pagesArray = $this->_model->selectPagesIdsAndNavigationName();
			$formsArray = $this->_model->selectAllForms();
			$featuredAreas = $this->getFeaturedAreasNameAsString();
			$this->view->downloadFiles = RCMS_Tools_FilesystemTools::scanDir($this->_config->website->website->path.$this->_config->website->website->downloads);
			$this->view->fa = array_keys($this->_model->selectFeaturedAreasNames());
			$this->view->fp = $this->_model->SelectAllPages();
			$this->view->forms = $formsArray;
			$this->view->pages = $pagesArray;
			$this->view->listFolders = RCMS_Tools_FilesystemTools::getDirectories($this->_config->website->website->path.$this->_config->website->website->images);
			$this->view->galleries = RCMS_Tools_FilesystemTools::getDirectories($this->_config->website->website->path.$this->_config->website->website->galleries);
			$this->view->variables = $this->_model->selectAllVariables();
			$widthImgs = $this->_model->selectConfigForImage();
			$this->view->widthSmallImg = $widthImgs['img_small']['value'];
			$this->view->widthMediumImg = $widthImgs['img_medium']['value'];
			$this->view->widthLargeImg = $widthImgs['img_large']['value'];
			$this->_linkListUrlForTinyMCEAction();
			RCMS_Tools_FilesystemTools::createMediaListForTinyMce();
			$this->view->listCategories = $this->_model->selectAllCategories();
            $this->view->users = $this->_model->selectAllUsers();
			$form->getElement('featuredareas')->setValue($featuredAreas);
			//inspired form
			$inspiredForm = new RCMS_Form_InspiredForm();
			$inspiredForm->getElement('h1')->setValue($page->getH1Tag());
			$inspiredForm->setDecorators(array(
				array('ViewScript', array('viewScript' => 'forms/inspired.phtml'))
			));
			if($page->getProtected()) {
				$this->view->protected = true;
			}

			$this->view->inspiredForm = $inspiredForm;
			$this->view->currentPageId = $page->getId();
			$this->view->currentNavigationName = trim($page->getNavName());
			//end of inspired form
		}
		elseif ($this->getRequest()->isPost()) {
			if ($this->view->form->isValid($this->getRequest()->getParams())) {
				$containerFormData = $this->view->form->getValues();
				//$container->setType(RCMS_Object_Container_Container::C_TYPE_CONTENT);
				$container->setContent($containerFormData['admincontentarea']);
				$container->setPublished($containerFormData['publish_content']);
                $container->setIsBlog($containerFormData['blog']);
				$date = '';
				if (isset($containerFormData['publish_content']) && $containerFormData['publish_content'] == 1) {
					$date = $this->generateTodaysDate();
				}
				else {
					if (isset($containerFormData['publish_on_date']) && $containerFormData['publish_on_date'] == 1) {
						if (trim($containerFormData['datepicker']) != '') {
							$date = $this->proccessPublishingDateToSql($containerFormData['datepicker']);
						}
					}
				}
				$container->setPublishingDate($date);
				$result = $container->save();
				$this->_session->resaveRaw = true;
				//making seo here.
				//$this->_seoParser->applyDeeplinks($container->getId())
				if(!$this->_seoParser->applyDeeplinksPerPage($container->getId())) {
					$this->_seoParser->setContentForParsing($container->getContent());
					$this->_seoParser->updateLinkReference($container->getId());
				}
                if ($container->isBlog()) {
                    $this->_pingBlogs($page);
                }
				//$this->_seoParser->replaceDeeplinksInContent();
				echo 'success'; return;
			}
		}
		echo $this->_translator->processScreen($this->view->render($this->getViewScript()));
	}

	public function addcodeAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$form = new RCMS_Form_CodeForm();
		$form->setDecorators(array(
			array('ViewScript', array('viewScript' => 'forms/addcode.phtml'))
		));
		$this->view->form = $form;
		$pageId = $this->getRequest()->getParam('pageId');
		if(empty ($pageId)) {
			$pageId = 0;
		}
		else {
			$this->view->pId = $pageId;
		}
		$name = $this->getRequest()->getParam('name');
		$this->view->name = $name;
		if($this->getRequest()->isPost()) {
			if($this->view->form->isValid($this->getRequest()->getParams())) {
				$user = unserialize($this->_session->currentUser);
				$codeFormData = $this->view->form->getValues();
				$container = new RCMS_Object_Container_Container();
				$container->setName($name);
				$container->setType(RCMS_Object_Container_Container::C_TYPE_CODE);
				$container->setContent($this->getRequest()->getParam('inlinecode'));
				$container->setUserId($user->getId());
				$container->setPageId($pageId);
				$container->setPublishingDate(date('Y-m-d H:i:s', time()));
				$container->setId($container->save());
				echo '<script typ="text/javascript">top.location.reload();</script>';
			}
		}
		$content = $this->_translator->processScreen($this->view->render($this->getViewScript()));
		$this->_helper->viewRenderer->setNoRender(true);
		echo $content;
	}

	public function editcodeAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$form = new RCMS_Form_CodeForm();
		$form->setDecorators(array(
			array('ViewScript', array('viewScript' => 'forms/editcode.phtml'))
		));
		$this->view->form = $form;
		$containerId = $this->getRequest()->getParam('id');
		$this->view->containerId = $containerId;
		$container = new RCMS_Object_Container_Container($containerId);
		$form->getElement('inlinecode')->setValue($container->getContent());
		if($this->getRequest()->isPost()) {
			if($this->view->form->isValid($this->getRequest()->getParams())) {
				$codeFormData = $this->view->form->getValues();
				$container->setType(RCMS_Object_Container_Container::C_TYPE_CODE);
				$container->setContent($codeFormData['inlinecode']);
				$result = $container->save();
				echo '<script typ="text/javascript">top.location.reload();</script>';
			}
		}
		$content = $this->_translator->processScreen($this->view->render($this->getViewScript()));
		$this->_helper->viewRenderer->setNoRender(true);
		echo $content;
	}

	public function addheaderAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$form = new RCMS_Form_HeaderForm();
		$form->setDecorators(array(
			array('ViewScript', array('viewScript' => 'forms/addheader.phtml'))
		));
		$this->view->form = $form;
		$pageId = $this->getRequest()->getParam('pageId');
		if(empty ($pageId)) {
			$pageId = 0;
		}
		else {
			$this->view->pId = $pageId;
		}
		$name = $this->getRequest()->getParam('name');
		$this->view->name = $name;

		if(!$this->getRequest()->isPost()) {
			$ctype = $this->getRequest()->getParam('type');
			$form->getElement('ctype')->setValue($ctype);
		}
		if($this->getRequest()->isPost()) {
			if($this->view->form->isValid($this->getRequest()->getParams())) {
				$user = unserialize($this->_session->currentUser);
				$containerFormData = $this->view->form->getValues();
				$container = new RCMS_Object_Container_Container();
				$container->setName($name);
				$ctype = $containerFormData['ctype'];
				$container->setType(($ctype && $ctype == RCMS_Object_Container_Container::C_TYPE_STATICHEADER) ? RCMS_Object_Container_Container::C_TYPE_STATICHEADER : RCMS_Object_Container_Container::C_TYPE_HEADER);
				$container->setContent(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('admincontentarea')));
				$container->setUserId($user->getId());
				$container->setPageId($pageId);
				$container->setPublishingDate(date('Y-m-d H:i:s', time()));
				$container->setId($container->save());
				$this->_session->resaveRaw = true;
				echo 'success'; exit();
			}
		}
		$content = $this->_translator->processScreen($this->view->render($this->getViewScript()));
		$this->_helper->viewRenderer->setNoRender(true);
		echo $content;
	}

	public function editheaderAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$form = new RCMS_Form_HeaderForm();
		$form->setDecorators(array(
			array('ViewScript', array('viewScript' => 'forms/editheader.phtml'))
		));
		$this->view->form = $form;
		$containerId = $this->getRequest()->getParam('id');
		$this->view->containerId = $containerId;
		$container = new RCMS_Object_Container_Container($containerId);
		$form->getElement('headertext')->setValue($container->getContent());
		if($this->getRequest()->isPost()) {
			if($this->view->form->isValid($this->getRequest()->getParams())) {
				$containerFormData = $this->view->form->getValues();
				//$container->setType(RCMS_Object_Container_Container::C_TYPE_HEADER);
				$container->setContent(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('admincontentarea')));
				$result = $container->save();
				$this->_session->resaveRaw = true;
				echo 'success'; exit();
			}
		}
		$content = $this->_translator->processScreen($this->view->render($this->getViewScript()));
		$this->_helper->viewRenderer->setNoRender(true);
		echo $content;
	}

	/**
	 * This function is generate link list for TinyMCE
	 *
	 * @return void
	 */
	private function _linkListUrlForTinyMCEAction() {
		$fileName = $this->_config->website->website->path . 'system/js/tiny_mce/link_list.js';
		try {
			if(file_exists($fileName)) {
				$draftCategoryId = $this->_model->selectDraftCategoryId();
				$pageListData = $this->_model->selectAllPages();

				$linkList = array();
				foreach($pageListData as $key=>$data) {
					if($data['is_404page'] == 1 || ($draftCategoryId && $data['parentCategoryId'] == $draftCategoryId) ) {
						continue; //removing drafts and 404 from pages list
					}
					array_push($linkList,
						sprintf('["%s","%s%s.html~%s"]'
							, addslashes($data['nav_name'])
							, $this->getWebSiteUrl()
							, $data['url']
							, addslashes( $data['h1'] )
							)
						);
				}

				$strPageList = sprintf('var tinyMCELinkList = new Array(%s);', implode(", ", $linkList));

				if(false === file_put_contents($fileName, $strPageList)) {
					throw new Exception("Can't save file ($fileName).");
				}
			} else {
				throw new Exception("Can't find file ($fileName) or this file doesn't exist.");
			}
		}
		catch (Exception $e) {
			echo $e->getMessage();
		}
	}
	/**
	 * This function generates tomorrows date
	 * @return <date>
	 */
	public function generateTomorrowsDate() {
		$date = date('m-d-Y');
		$dateArray = explode("-", $date);
		$tomorrowsDate = date("Y-m-d", mktime(0, 0, 0, $dateArray[0], ($dateArray[1])+1,$dateArray[2]));
		return $tomorrowsDate;
	}
	/**
	 * This function generates todays date
	 * @return <date>
	 */
	public function generateTodaysDate() {
		return date('Y-m-d');
	}
	/**
	 * This function generates date to sql format
	 * @return <date>
	 */
	public function proccessPublishingDateToSql($date) {
		$dateArray = explode("-", trim($date));
		$date = date("Y-m-d", mktime(0, 0, 0, $dateArray[0], $dateArray[1],$dateArray[2]));
		return $date;
	}
	/**
	 * This function generates date from sql format
	 * @return <date>
	 */
	public function proccessPublishingDateFromSql($date) {
		$dateArray = explode("-", trim($date));

		$timeArray = explode(" ", $dateArray[2]);

		$day = $timeArray[0];
		$date = date("m-d-Y", mktime(0, 0, 0, $dateArray[1], $day,$dateArray[0]));
		return $date;
	}

	public function getFeaturedAreasNameAsString() {
		$result = $this->_model->selectFeaturedAreasNames();
		$str="";
		if($result) {
			foreach ($result as $key=>$value) {
				$str.=$key."~";
			}
		}
		return trim($str);
	}


	public function addgooglemapAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$form = new RCMS_Form_GooglemapForm();
		$form->setDecorators(array(
			array('ViewScript', array('viewScript' => 'forms/addgooglemap.phtml'))
		));
		$this->view->form = $form;


		$name = $this->getRequest()->getParam('name');
		$this->view->name = $name;

	if($this->getRequest()->isPost()) {
			if($this->view->form->isValid($this->getRequest()->getParams())) {

				if( trim($this->getRequest()->getParam('googlemapcode'))=="")
				{
					echo '<script> $("#googlemap-empty").show();</script>';
					return;
				}
				$user = unserialize($this->_session->currentUser);
				$containerFormData = $this->view->form->getValues();
				$container = new RCMS_Object_Container_Container();
				$container->setName($name);
				$container->setType(RCMS_Object_Container_Container::C_TYPE_GOOGLEMAP);
				$container->setContent(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('googlemapcode')));
				$container->setUserId($user->getId());
				$container->setPageId(0);
				$container->setPublishingDate(date('Y-m-d H:i:s', time()));
				$id = $container->save();
				$container->setId($id);
				if($id){
				echo '<script> parent.tb_remove();  top.location.reload();</script>';
				}
			}
		}
		$content = $this->_translator->processScreen($this->view->render($this->getViewScript()));
		$this->_helper->viewRenderer->setNoRender(true);
		echo $content;
	}

	public function editgooglemapAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$form = new RCMS_Form_HeaderForm();
		$form->setDecorators(array(
			array('ViewScript', array('viewScript' => 'forms/editheader.phtml'))
		));
		$this->view->form = $form;
		$containerId = $this->getRequest()->getParam('id');
		$this->view->containerId = $containerId;
		$container = new RCMS_Object_Container_Container($containerId);
		$form->getElement('headertext')->setValue($container->getContent());
		if($this->getRequest()->isPost()) {
			if($this->view->form->isValid($this->getRequest()->getParams())) {
				$containerFormData = $this->view->form->getValues();
				//$container->setType(RCMS_Object_Container_Container::C_TYPE_HEADER);
				$container->setContent(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('admincontentarea')));
				$result = $container->save();
				echo 'success'; exit();
			}
		}
		$content = $this->_translator->processScreen($this->view->render($this->getViewScript()));
		$this->_helper->viewRenderer->setNoRender(true);
		echo $content;
	}


    public function getgroupsandbrandsAction()
    {
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        if ($this->getRequest()->isPost()) {
            $shoppingGroups = $this->_model->selectGroups();
            $shoppingBrands = $this->_model->selectBrands();
            $shoppingProducts = $this->_model->selectAllProducts();
            $outGroups = '';
            $outBrands = '';
            $outProducts = '';
            if (is_array($shoppingGroups) && count($shoppingGroups) > 0) {
                foreach ($shoppingGroups as $group) {
					$group['name'] = RCMS_Tools_Tools::convertEncoding($group['name']);
                    $outGroups .= '<p title="' . $group['name'] . '" id="group-'.$group['id'].'"><input type="checkbox" name="group-'.$group['id'].'" onclick="Sc.getProducts(this);" /> ';
                    $outGroups .= '<span>'.(strlen($group['name'])<= 25 ?  $group['name'] : substr($group['name'],0,25).'...').'</span></p>'."\n";
                }
            }
            if (is_array($shoppingBrands) && count($shoppingBrands) > 0) {
                foreach ($shoppingBrands as $brand) {
					//$brand['brand'] = RCMS_Tools_Tools::convertEncoding($brand['brand']);
                    $outBrands .= '<p title="'.RCMS_Tools_Tools::convertEncoding($brand['brand']).'"><input type="checkbox" name="brand-'.RCMS_Tools_Tools::convertEncoding($brand['brand']).'" onclick="Sc.getProducts(this);" /> ';
                    $outBrands .= '<span>'.(strlen($brand['brand'])<= 7 ? RCMS_Tools_Tools::convertEncoding($brand['brand']) : substr(RCMS_Tools_Tools::convertEncoding($brand['brand']),0,7).'...').'</span></p>';
                }
            }
            $webSiteUrl = $this->_config->website->website->url;
            if (is_array($shoppingProducts) && count($shoppingProducts) > 0) {
                foreach ($shoppingProducts as $product) {
                    $outProducts .= '<div class="shoppingproduct">';
                    $outProducts .= '<div class="block1"><img src="'.$webSiteUrl.$product['photo'].'" onclick="Sc.addVariableProductToContent(\''.$product['id'].'\', \''. addslashes($product['name']) .'\');" title="add product"/></div>';
                    $outProducts .= '<p class="productbrand" title="'.$product['brand'].'">'.$product['brand'].'</p>';
                    $outProducts .= '<div class="block2"><p class="productname" title="'.$product['name'].'" style="overflow:hidden;height:17px;">'.$product['name'].'</p>';
                    $outProducts .= '<p class="productitemid" title="'.$product['item_id'].'">'.$product['item_id'].'</p></div></div>'."\n";
					}
            }
			$outProducts = RCMS_Tools_Tools::convertEncoding($outProducts);
            echo json_encode(array('groups' => $outGroups, 'brands' => $outBrands, 'products' => $outProducts)); return;
        }
    }

    public function getproductsforgrouporbrandAction()
    {
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        if ($this->getRequest()->isPost()) {
            $flag = $this->getRequest()->getParam('flag');
            if ($flag == 'group') {
                $id = (int) $this->getRequest()->getParam('id');
                $data = $this->_model->selectProductsForGroup($id);
            }
            if ($flag == 'brand') {
                $name = trim($this->getRequest()->getParam('name'));
                $data = $this->_model->selectBrandByName($name);
            }
            if (is_array($data) && count($data) > 0) {
                echo json_encode($data); return;
            }
            echo json_encode(array()); return;
        }
    }

    public function getheaderforblogAction()
    {
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);

        if ($this->getRequest()->isPost() && $this->_session->isLogged) {
            $id = (int) $this->getRequest()->getParam('id');
            $page = new RCMS_Object_Page_Page($id);
            $href = '#';
            if ($page->getId() > 0) {
                $href = $this->_config->website->website->url.$page->getUrl().'.html';
            }
            $user = unserialize($this->_session->currentUser);
            echo '<div class="titleblog"><a href="'.$href.'">Published on '.date('Y-m-d').' by '.$user->getNickName().'</a></div>';
        }
    }

    private function _pingBlogs(RCMS_Object_Page_Page $page)
    {
        $pageURL = $this->_config->website->website->url.$page->getUrl().'.html';
        $modelPromote = new Backend_PromoteModel();
        $services = $modelPromote->selectAllService();

        if (is_array($services) && count($services) > 0) {
            foreach ($services as $service) {
                try {
                    $xmlRpcClient = new Zend_XmlRpc_Client($service['url']);
                    $xmlRpcClient->doRequest(new Zend_XmlRpc_Request('weblogUpdates.ping', array($page->getH1Tag(), $pageURL)));
                    unset ($xmlRpcClient);
                } catch (Exception $e) {}
            }
        }
    }

}